package com.linktrip.devicemanager.server;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.linktrip.devicemanager.dao.IDeviceLogDao;
import com.linktrip.devicemanager.entity.DeviceInfo;
import com.linktrip.devicemanager.entity.DeviceLog;
import com.linktrip.devicemanager.util.ToolKits;

@Service(value = "deviceLogService")
@SuppressWarnings("rawtypes")
public class DeviceLogService {

	Logger log = LoggerFactory.getLogger(DeviceLogService.class);

	@Resource
	IDeviceLogDao dao;

	@Resource
	DeviceService deviceService;

	public List<DeviceLog> listDeviceLog() {
		return dao.getAllDeviceLogs();
	}

	public List<DeviceLog> listDeviceLogPaging(Map map) {
		return dao.paging(map);
	}

	public int totals(Map map) {
		return dao.totals(map);
	}
	
	public int totals(String no){
		return dao.total(no);
	}

	public List<DeviceLog> listDeviceLogByNo(String no) {
		return dao.getDeviceLogsByNo(no);
	}

	public List<DeviceLog> getDeviceLogByDeviceNo(String no) {
		return dao.getDeviceLogsByNo(no);
	}

	public boolean addDeviceLog(DeviceLog entity) {
		try {
			DeviceInfo device = new DeviceInfo();
			DeviceInfo tmp =ToolKits.getDeviceInfo(entity.getDevice_no());
			if (tmp == null || tmp.getId() <= 0) {
				log.warn("deviceId:{} not exsits!!! do nothing...",entity.getDevice_no() );
				return false;
			}
			device.setId(tmp.getId());
			device.setDevice_no(entity.getDevice_no());
			device.setBattery_status(entity.getBattery_stat());
			device.setVbattery(entity.getVbattery());
			//int charge = (entity.getCharge() & 0x1) == 1 ? 1 : 2;
			//device.setCharge(charge);
			device.setCharge(entity.getCharge());
			device.setFalut(entity.getMode());
			device.setLatitude(entity.getLatitude());
			device.setLongitude(entity.getLongitude());
			device.setStatus(entity.getLock_status());
			device.setTemperature(entity.getTemperature());
			device.setVbus(entity.getVbus());
			device.setUpdate_date(System.currentTimeMillis());
			device.setSys_version(entity.getSys_version());
			device.setHdware_version(entity.getHdware_version());
			device.setNa1(entity.getNa1());
			device.setNa2(entity.getNa2());
			deviceService.updateDevice(device);
			dao.addDeviceLogs(entity);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean removeDeviceLog(String no) {
		return dao.remove(no) > 0;
	}

}
